package com.example.amazlinglistview.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.accounts.NetworkErrorException;

public class NetUtils {

	public static String getJson(String address) throws Exception {
		// 创建一个URL对象
		URL url = new URL(address);
		// 使用URL对象的openConnection()方法打开一个连接对象（未连接）
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		// 设置请求超时时间（如果超时未响应，抛出异常）
		conn.setConnectTimeout(30000);
		// 获取服务器响应数据（开始连接）
		int code = 0;
		try {
			code = conn.getResponseCode();
		} catch (Exception e) {
			new Exception("code错误："+e.toString());
		}
		if (code == 200) {
			InputStream in = conn.getInputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int len = -1;
			while ((len = in.read(buf)) != -1) {
				baos.write(buf, 0, len);
			}
			in.close();
			baos.close();

			String json = new String(baos.toByteArray());
			return json;
		}
		throw new NetworkErrorException("连接出错：" + code);
	}
}
